import axios from 'axios';
import RankItemEchart from 'components/rank-item-echart';
import tagTestData from 'data/tagTestData';
import { makeAutoObservable } from 'mobx';
/**
 * 标签store
 * 描述：标签存储
 * 调用：活动页面及标签页面
 * 时间：20220402
 */
class TagStore {
    constructor() {
        makeAutoObservable(this)
    }
    //活动标签编辑时会给画布上的标签一个自动递增的key值
    autoKeyIndex =  0
    /**
     * 活动标签编辑时画布上的已选标签
     * {
            key: "key",
            fromKey:"origin tag's key",
            fromName:"name of origin tag",
            name:"name of used tag",
            operation:"operation",
            operationCata:"operation category",
            value:"value"
        }
     */
    usedTags  =  []
    //活动标签编辑时选中的标签
    selectedKey  =  0
    /**
     * 标签选择菜单
     * 描述：活动标签编辑时左侧提供标签选择的菜单
     * 构造：tagMenuSource = [{
            title:"标签名称",
            key:"主键",
            icon:"图标",
            children:[{ 子菜单
                title:"图标",
                key:"主键",
                icon:"图标"
                }]
            }]
     */
    tagMenuSource = []
    /**
     * 所有标签信息
     * 描述：所有标签信息
     * 构造：allTags =  [
            {
                name:"标签名称",
                key:"主键",
                icon:"图标"
            }]
     */
    allTags =  []
    /**
     * 推荐标签信息
     * 推荐标签信息
     * recommendTags = [
        {
            fromKey:'衍生标签来源标签的key',
            key:"主键",
            name:"标签名",
            rate: 推荐率
            
         }]
     */
    recommendTags = []

    //标签中心左侧菜单选中标签的标签名(用于Echart的传参)
    tagName = ""
    //标签中心左侧菜单选中标签的标签信息
    tagDetail = {}
    //标签中心选中标签的关联活动
    relatedActivityItems = []
    //标签中心选中标签的衍生标签（年龄 的衍生标签有 年龄>10，年龄<35 等）
    derivedTagItems = []
    //标签中心选中标签是否已上架
    tagStatusChecked = false
    //标签中心标签描述信息
    tagDescription = ""
    //推荐标签添加时查询后端衍生标签
    derivedTag={}
    
    
  

    /**
     * 标签关系图
     * 描述：营销效果中心标签关系数据
     * 构造：
     */
    tagsRelationshipData = []
    
    apiRelationship = async() => {
        this.tagsRelationshipData = tagTestData.tagRelationshipTestData
        axios.get(axios.defaults.baseURL + `/api/tag/relationship`).then(
            response => {
                this.tagsRelationshipData = response.data
            },
            error => {
                console.log('ERROR',error) 
            }
        )

    }
    apiAllTags = async() => {
        this.allTags = tagTestData.allTagsTestData
        axios.get(axios.defaults.baseURL + `/api/tag/all`).then(
            response => {
                this.allTags = response.data
            },
            error => {
                console.log('ERROR',error) 
            }
        )

    }

    apiTagMenuSourceAll = async() => {
        
        axios.get(axios.defaults.baseURL + `/api/tag/menu`).then(
            response => {
                this.tagMenuSource = response.data
            },
            error => {
                this.tagMenuSource = tagTestData.tagMenuTestData
                console.log('ERROR',error) 
            }
        )

    }
    apiTagMenuSourceOn = async() => {
        
        axios.get(axios.defaults.baseURL + `/api/tag/menu`).then(
            response => {
                this.tagMenuSource = response.data
                this.tagMenuSourceFilter("on")
            },
            error => {
                this.tagMenuSource = tagTestData.tagMenuTestData
                this.tagMenuSourceFilter("on")
                console.log('ERROR',error) 
            }
        )

    }
    tagMenuSourceFilter(status){
        let  tagMenuSourceFilter = this.tagMenuSource.map(tagMenuParent=>{
            let tagMenuParentFilter = tagMenuParent
            let children = tagMenuParent.children.filter(item=>{
                if(status && item.status !== status){
                    return false
                }
                return true
            })

            tagMenuParentFilter.children = children
            return tagMenuParentFilter
        })
        console.log(tagMenuSourceFilter)
        this.tagMenuSource = tagMenuSourceFilter
    }

    
    apiRecommendTags = async() => {
        // this.recommendTags = tagTestData.recommendTagsTestData
        const tags = this.usedTags.map(item=>{
            return item.name
        })
        
        axios.post(axios.defaults.baseURL + `/api/tag/recommend`,tags).then(
            response => {
                console.log("OK")
                console.log(response.data)
                this.recommendTags = response.data
                
            },
            error => {
                console.log('ERROR',error)
                this.recommendTags = tagTestData.recommendTagsTestData
            }
        )
    }

    apiTagDetail = async(tagCode) => {
          
        axios.get(axios.defaults.baseURL + `/api/tag/detail?tagCode=${tagCode}`).then(
            response => {
                
                this.tagDetail = response.data
                this.setTagName(this.tagDetail.name)
                //设置标签上架状态
                this.setTagStatusChecked(this.tagDetail.status==='on'?true:false)
                //设置标签描述信息
                this.setTagDescription(this.tagDetail.description)
                
            },
            error => {
                this.tagDetail = tagTestData.tagDetailsTestData.find(item => item.key === tagCode) || {}
                this.setTagName(this.tagDetail.name)
                //设置标签上架状态
                this.setTagStatusChecked(this.tagDetail.status==='on'?true:false)
                //设置标签描述信息
                this.setTagDescription(this.tagDetail.description)
                console.log('ERROR',error)
            }
        )
    }
    apiTagDrived = async(tagCode) => {
        const derivedTag = tagTestData.derivedTagsTestData.find(item => item.key === tagCode)
        if(derivedTag){
            this.derivedTagItems =  derivedTag.tags
        }else{
            this.derivedTagItems = []
        }
        axios.get(axios.defaults.baseURL + `/api/tag/derived?tagCode=${tagCode}`).then(
            response => {
                this.derivedTagItems = response.data
                
            },
            error => {
                console.log('ERROR',error)
                
            }
        )

    }

    apiTagActivity = async(tagCode) => {
        const relatedActivity = tagTestData.relatedActivitiesTestData.find(item => item.key === tagCode)
        if (relatedActivity){
            this.relatedActivityItems = relatedActivity.activities
        }else{
            this.relatedActivityItems = []
        }
        axios.get(axios.defaults.baseURL + `/api/tag/activity?tagCode=${tagCode}`).then(
            response => {
                this.relatedActivityItems = response.data
            },
            error => {
                console.log('ERROR',error)
                

            }
        )

    }
    /**
     * 从推荐标签添加已选标签
     * @param {*} recommendTag 推荐标签
     */
    apiAddRecommendTagToUsedTags = async(recommendKey) =>{
    
        axios.get(axios.defaults.baseURL + `/api/tag/derived_tag_by_key?derivedTagCode=${recommendKey}`).then(
            response => {
                this.derivedTag = response.data
                this.usedTags=[...this.usedTags,this.derivedTag]
                
            },
            error => {
                console.log('ERROR',error) 
            }
        )

        this.setUsedTags(this.usedTags.slice()) 

    }
    
   

    /**
     * 设置已选标签
     * @param {*} newTag 新标签
     */
    setUsedTags(newTags){
        this.usedTags = newTags
        
    }
    setRecommendTags(newTags){
        this.recommendTags = newTags
    }
    /**
     * 设置标签自增key值
     * @param {*} index 
     */
    setAutoKeyIndex(index){
        this.autoKeyIndex = index
    }
    /**
     * 设置选中标签key
     * @param {*} key 
     */
    setSelectedKey(key){
        this.selectedKey = key
    }
    /**
     * 活动标签编辑对标签添加操作
     * @param {*} operation 操作类型(compare,judge,enum)
     * @param {*} operationSign 操作类型符号(">","<"...)
     */
    setUsedTagByOperation(operation,operationSign){
        
        let selectedTagInEditAreaIndex = this.usedTags.findIndex(item=>item.key === this.selectedKey)
        let selectedTagInEditArea = this.usedTags[selectedTagInEditAreaIndex]
        if(!selectedTagInEditArea){
            return ;
        }
        selectedTagInEditArea.operationCata = operation
        selectedTagInEditArea.operation = operationSign
        if (selectedTagInEditArea.value){
            selectedTagInEditArea.name = selectedTagInEditArea.fromName +" "+ selectedTagInEditArea.operation +" "+ selectedTagInEditArea.value
        }else {
            selectedTagInEditArea.name = selectedTagInEditArea.fromName +" "+ selectedTagInEditArea.operation
        }
        this.setUsedTags(this.usedTags.slice()) 
        
    }
    /**
     * 活动标签编辑对标签添加值
     * @param {*} value 值
     */
    setUsedTagByInput(value){
        let selectedTagInEditAreaIndex = this.usedTags.findIndex(item=>item.key === this.selectedKey)
        let selectedTagInEditArea = this.usedTags[selectedTagInEditAreaIndex]
        selectedTagInEditArea.value = value

        selectedTagInEditArea.name = selectedTagInEditArea.fromName +" "+ selectedTagInEditArea.operation +" "+ selectedTagInEditArea.value
        this.setUsedTags(this.usedTags.slice()) 
    }

    /**
     * 根据key值删除已选标签
     * @param {*} key 
     */
    setUsedTagByDelete(key){
        
        const selectedTagInEditAreaIndex = this.usedTags.findIndex(item=>item.key === key)
        
        this.usedTags.splice(selectedTagInEditAreaIndex,1)
        this.setUsedTags(this.usedTags.slice())
    }
    
    /**
     * 标签中心根据选择标签菜单项更新标签明细的值
     * @param {*} key 选中标签的key
     */
    setTagDetailByKey(key){
        //设置标签名
        this.setTagName("")
        //设置标签上架状态
        this.setTagStatusChecked(false)
        //设置标签描述信息
        this.setTagDescription("")
        
        key && this.apiTagDetail(key)
        
        
    }
    /**
     * 标签中心根据选择标签菜单项更新关联活动的值
     * @param {*} key 选中标签的key
     */
    setRelatedActivityByKey(key){
        key && this.apiTagActivity(key)
        
        
    }
    /**
     * 标签中心根据选择标签菜单项更新衍生标签的值
     * @param {*} key 选中标签的key
     */
    setDerivedTagByKey(key){
        this.apiTagDrived(key)
    }
    /**
     * 标签中心设置标签名
     * @param {*} name 
     */
    setTagName(name){
       this.tagName = name 
    }
    /**
     * 标签中心设置标签是否上架的信息
     * @param {*} checked 是否上架
     */
    setTagStatusChecked(checked){
        this.tagStatusChecked = checked
    }

    
    /**
     * 标签中心设置标签描述信息
     * @param {*} description 
     */
    setTagDescription(description){
        this.tagDescription = description
    }


    apiTagOn = async(tagCode) => {
        axios.get(axios.defaults.baseURL + `/api/tag/on?tagCode=${tagCode}`).then(
            response => {
                console.log("OK")
                alert("标签"+tagCode+"已上线")
                this.apiTagDetail(tagCode)
                
                
            },
            error => console.log('ERROR',error)
        )

    }

    apiTagOff = async(tagCode) => {
        axios.get(axios.defaults.baseURL + `/api/tag/off?tagCode=${tagCode}`).then(
            response => {
                console.log("OK")
                alert("标签"+tagCode+"已下线")
                this.apiTagDetail(tagCode)
                
            },
            error => console.log('ERROR',error)
        )

    }

    apiTagDescription = async(tagCode,description) => {
        axios.get(axios.defaults.baseURL + `/api/tag/description?tagCode=${tagCode}&&description=${description}`).then(
            response => {
                console.log("OK")
                alert("标签"+tagCode+"的描述信息已更改")
                this.apiTagDetail(tagCode)
                
            },
            error => console.log('ERROR',error)
        )

    }

    apiCreateTag = async(tagCode,name,category) => {
        const basTag = {
            tagCode: tagCode,
            name: name,
            category: category
        }

        console.log(JSON.stringify(basTag))
        axios.post(axios.defaults.baseURL + `/api/tag/create`,basTag).then(
            response => {
                console.log("OK")
                alert(response.data)
                this.apiTagMenuSourceAll()
                
                
            },
            error => console.log('ERROR',error)
        )

    }

    apiDeleteTag = async(tagCode) => {
        const info = {'tagCode':tagCode}
        axios.get(axios.defaults.baseURL + `/api/tag/delete?tagCode=${tagCode}`).then(
            response => {
                console.log("OK")
                alert(response.data)
                this.apiTagMenuSourceAll()
                
            },
            error => console.log('ERROR',error)
        )

    }
}
const tagStore = new TagStore()
export default tagStore